extends CanvasLayer

@onready var deployment_graph: GridContainer = $MainContainer/CenterPanel/LeftPanel/DeploymentGraph/GridContainer/GridContainer
@onready var count_number: Label = $MainContainer/CenterPanel/LeftPanel/LeftCount/CountNumber
@onready var tech_container: GridContainer = $MainContainer/CenterPanel/RightPanel/TechnologiesContainer/GridContainer
@onready var equip_container: GridContainer = $MainContainer/CenterPanel/RightPanel/EquipmentsContainer/GridContainer
@onready var confirm_button: Button = $MainContainer/BottomPanel/Confirm
@onready var mission_label: Label = $MainContainer/TopPanel/Label
@onready var minion_flow: HBoxContainer = $MainContainer/TopPanel/MinionFlow


var left_troop_count := 0
var _current_tooltip: Control

# Called when the node enters the scene tree for the first time.
func _ready() -> void:
	left_troop_count = GameData.army_data.max_count
	count_number.text = str(left_troop_count)
	update_troop_cards()
	_load_technologies()
	_load_equipments()
	_generate_level_data()
	_update_confirm_button_state()
	_update_mission_label()
	_update_minion_flow()



# 返回主页面
func _on_cancel_pressed():
	get_tree().change_scene_to_file("res://game/01_scenes/interface/main_menu.tscn")

# 随机分配兵力
func _on_random_pressed():
	var total = GameData.army_data.max_count
	var cards = deployment_graph.get_children().filter(func(c): return c is TroopCard)
	
	# 先全部清零
	for card in cards:
		card.current_count = 0
	
	# 随机分配算法（保证完全分配）
	var rng = RandomNumberGenerator.new()
	var remaining = total
	while remaining > 0:
		var card = cards[rng.randi() % cards.size()]
		card.current_count += 1
		remaining -= 1
	left_troop_count = 0
	# 更新显示
	_on_troop_amount_requested(0, null) # 触发一次刷新

# 确认并进入房间场景
func _on_confirm_pressed():
	# 保存兵力配置
	var army_data = GameData.army_data
	army_data.troops.clear()
	for card in deployment_graph.get_children():
		if card is TroopCard and card.current_count > 0:
			army_data.add_troop(card.troop_type, card.current_count, card.scene_path, card.icon_path)
	
	# 加载战斗房间
	get_tree().change_scene_to_file("res://game/01_scenes/rooms/room.tscn")
	
func _load_technologies():
	_clear_container(tech_container)
	
	for tech in GameData.army_data.technologies:
		_create_tech_icon(tech)

func _load_equipments():
	_clear_container(equip_container)
	
	for equip in GameData.army_data.equipments:
		_create_equip_icon(equip)

func _clear_container(container: GridContainer):
	for child in container.get_children():
		child.queue_free()

func _create_tech_icon(tech: TechnologyResource):
	var icon := TextureRect.new()
	icon.custom_minimum_size = Vector2(32, 32)
	icon.stretch_mode = TextureRect.STRETCH_SCALE
	var description = str(tech.display_name, '\n', tech.description)
	_setup_icon(icon, tech.icon_path, description)
	tech_container.add_child(icon)

func _create_equip_icon(equip: EquipmentResource):
	var icon := TextureRect.new()
	icon.custom_minimum_size = Vector2(16, 16)
	icon.stretch_mode = TextureRect.STRETCH_SCALE
	var description = str(equip.display_name, '\n', equip.description)
	_setup_icon(icon, equip.icon_path, equip.description)
	equip_container.add_child(icon)

# 修改_setup_icon方法
func _setup_icon(icon: TextureRect, icon_path: String, tooltip: String):
	# 添加纹理加载逻辑
	if ResourceLoader.exists(icon_path):
		icon.texture = load(icon_path)
	else:
		push_warning("图标资源加载失败: %s" % icon_path)
		icon.texture = preload("res://game/03_assets/icons/default_icon.png") # 添加默认图标
	
	# 保持原有tooltip连接
	icon.mouse_entered.connect(_show_tooltip.bind(tooltip))
	icon.mouse_exited.connect(_hide_tooltip)
	

func _show_tooltip(text: String):
	# 实现自定义Tooltip场景
	var tooltip_scene = preload("res://game/01_scenes/interface/ui/tooltip.tscn")
	_current_tooltip = tooltip_scene.instantiate()
	_current_tooltip.get_node("Label").text = tr(text)
	add_child(_current_tooltip)
	_current_tooltip.global_position = get_viewport().get_mouse_position() + Vector2(20, 20)

func _hide_tooltip():
	if _current_tooltip:
		_current_tooltip.queue_free()
		_current_tooltip = null


func update_troop_cards():
	# 清空现有卡片
	for child in deployment_graph.get_children():
		child.queue_free()
		child.queue_redraw()

	# 动态创建所有兵种卡片
	for troop_key in GameData.available_troop_types:
		var troop_data = GameData.all_troop_types[troop_key]
		
		# 实例化卡片场景
		var card_scene = load("res://game/01_scenes/interface/army_deployment/troop_card.tscn")
		if not card_scene:
			push_warning("无法加载卡片场景")
			continue
			
		var card_instance = card_scene.instantiate()
		if not card_instance is TroopCard:
			push_warning("实例不是TroopCard类型")
			continue
		# 添加到布局容器
		deployment_graph.add_child(card_instance)
		# 初始化卡片属性
		card_instance.troop_type = troop_data["id"]
		
		# 连接信号（带参数绑定）
		card_instance.amount_requested.connect(_on_troop_amount_requested)
		
		# 设置初始显示状态
		card_instance.update_display(0, left_troop_count)
		card_instance.update_icon(troop_data["icon_path"])
		card_instance.scene_path = troop_data["scene_path"]
		

# 信号处理方法（修改后）
func _on_troop_amount_requested(delta: int, card: TroopCard) -> void:
	# 安全访问检查
	if card != null:
		# 获取当前卡片的实际数值
		var current = card.current_count
		
		# 计算可分配的实际变化量（考虑剩余兵力）
		var actual_delta = clamp(delta, - current, left_troop_count)
		
		# 更新卡片实际值
		card.current_count = current + actual_delta
		
		# 更新全局剩余兵力
		left_troop_count -= actual_delta
		count_number.text = str(left_troop_count)
	else:
		# 当card为null时强制刷新显示
		count_number.text = str(left_troop_count)
	
	# 重新计算所有卡片的可用最大值
	var total_allocated = _get_total_allocated()
	var actual_max_available = GameData.army_data.max_count - total_allocated
	
	# 刷新所有卡片状态
	for card_node in deployment_graph.get_children():
		if card_node is TroopCard:
			# 可用量 = 总上限 - 其他卡片分配量
			card_node.update_display(
				card_node.current_count,
				actual_max_available + card_node.current_count
			)
	_update_confirm_button_state()
# 新增辅助方法
func _get_total_allocated() -> int:
	var total = 0
	for card in deployment_graph.get_children():
		if card is TroopCard:
			total += card.current_count
	return total

func _generate_level_data():
	EnemyManager.generate_level_data(GameData.level_data.level_number)

func _update_confirm_button_state():
	var has_remaining = left_troop_count > 0
	
	confirm_button.disabled = has_remaining
	confirm_button.tooltip_text = tr("text.confirm_validation") if has_remaining else ""
	
	# 添加视觉反馈
	confirm_button.modulate = Color.DIM_GRAY if has_remaining else Color.WHITE


func _update_mission_label():
	# 获取关卡和房间信息
	var level_num = GameData.level_data.level_number
	var room_index = GameData.level_data.room_index
	
	# 构建翻译键
	var translation_key = "text.mission"
	# 设置任务标签文本（使用翻译系统）
	mission_label.text = tr(translation_key).format({
		"level": level_num,
		"room": room_index
	})

func _update_minion_flow():
	# 清空现有子节点
	for child in minion_flow.get_children():
		child.queue_free()
	
	# 遍历前6个房间
	for room_index in range(6):
		var room_data = GameData.level_data.room_queue[room_index]
		
		# 创建房间图标
		var room_icon = TextureRect.new()
		room_icon.custom_minimum_size = Vector2(32, 32)
		room_icon.stretch_mode = TextureRect.STRETCH_KEEP_ASPECT_CENTERED
		
		# 设置图标路径
		var icon_path = "res://game/03_assets/icons/room_%d.png" % (room_index + 1)
		if ResourceLoader.exists(icon_path):
			room_icon.texture = load(icon_path)
		else:
			room_icon.texture = preload("res://game/03_assets/icons/default_icon.png")
		
		# 生成tooltip文本
		var tooltip_text := ""
		for category in ["normal", "elite", "boss"]:
			var enemies = room_data[category]
			if not enemies.is_empty():
				tooltip_text += tr("enemy.%s" % category) + ":\n"
				for enemy_type in enemies:
					var count = enemies[enemy_type]
					tooltip_text += "  - %s x%d\n" % [tr("enemy.%s" % enemy_type), count]
		
		# 连接tooltip信号
		room_icon.mouse_entered.connect(_show_room_tooltip.bind(tooltip_text))
		room_icon.mouse_exited.connect(_hide_tooltip)
		
		minion_flow.add_child(room_icon)

func _show_room_tooltip(text: String):
	# 复用现有tooltip逻辑
	_show_tooltip(text)
